<?php
/**
 * Created by PhpStorm.
 * User: 李大爷
 * Date: 2019/3/1
 * Time: 18:14
 */

namespace app\controllers;


use app\models\Permission;
use yii\helpers\VarDumper;
use Yii;
use yii\web\NotFoundHttpException;

class PermissionController extends BaseController
{

    /**
     * 权限管理列表
     * @return string
     */
    public function actionIndex()
    {
        $data = Permission::tree();

        return $this->render('index',['data'=>$data]);
    }

    /**
     * 添加权限
     * @return string|\yii\web\Response
     */
    public function actionCreate()
    {
        $model = new Permission();
        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            $model->scenario = 'create';
            if ($model->load($data,'')&&$model->createPermission()){
                Yii::$app->session->setFlash('info','添加成功');
                return $this->redirect(['index']);
            }
        }
        $parent = $model->find()->where(['and','type=2','name like "%/*"'])->asArray()->all();
        return $this->render('create',['model'=>$model,'parent'=>$parent]);
    }

    /**
     * 编辑权限
     * @param $name
     * @return string|\yii\web\Response
     * @throws NotFoundHttpException
     */
    public function actionEdit($name)
    {
        $model = Permission::findOne(['name'=>$name]);
        if ($model===null){
            throw new NotFoundHttpException('权限不存在');
        }
        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            $model->scenario = 'edit';
            if ($model->load($data,'')&&$model->editPermission()){
                Yii::$app->session->setFlash('info','更新成功');
                return $this->redirect(['index']);
            }
        }
        $parent = $model->find()->where(['and','type=2','name like "%/*"'])->asArray()->all();
        foreach ($parent as &$p){
            $where = explode('/',$name);
            $p['selected'] = $p['name']==$where[0].'/*' && $where[1]!='*' ? 'selected' : '';
        }
        return $this->render('edit',['model'=>$model,'parent'=>$parent]);
    }

    /**
     * 删除权限
     * @param $name
     * @return \yii\web\Response
     */
    public function actionDestroy($name)
    {
        $auth = Yii::$app->authManager;
        $permission = $auth->getPermission($name);
        if ($permission === null){
            return $this->asJson(['code'=>1,'msg'=>'权限不存在']);
        }
        $where = explode('/',$name);
        if ($where[1]=='*'){
            $count = Permission::find()->where(['and','type=2','name !="'.$where[0].'/*"','name like "'.$where[0].'/%"'])->count();
            if ($count){
                return $this->asJson(['code'=>1,'msg'=>'存在子权限，禁止删除']);
            }
        }
        if ($auth->remove($permission)){
            return $this->asJson(['code'=>0,'msg'=>'删除成功']);
        }
        return $this->asJson(['code'=>1,'msg'=>'删除失败']);
    }

}